<template>
  <el-dialog
    :visible="value"
    :before-close="handleClose"
    :close-on-click-modal="false"
    append-to-body
    title="新增规格"
    width="800px">

    <div class="add-size">
      <el-table
        :data="formDataList"
        border
        width="760">
        <el-table-column
          v-for="(field, index) in fieldList"
          :key="index"
          :label="field.label">
          <template slot-scope="scope">
            <el-input
              v-model.trim="scope.row[field.prop]"
              :placeholder="autoGeneNumber ? '根据编号规则自动生成，支持手动输入' : ''"
              :maxlength="100"
              size="small" />
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="100">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="handleDelete(scope.$index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="add-column">
        <el-button
          type="text"
          @click="handleAddSize">
          + 添加规格
        </el-button>
      </div>

      <el-table
        :data="dataList"
        border
        width="760"
        class="system-table">
        <el-table-column
          type="index"
          width="60" />
        <el-table-column
          v-for="(field, index) in fieldList"
          :key="index"
          :label="field.label"
          :prop="field.prop"
          show-overflow-tooltip />
      </el-table>
    </div>

    <div
      slot="footer"
      class="dialog-footer">
      <el-button
        @click="handleClose">
        取 消
      </el-button>
      <el-button
        type="primary"
        @click="handleConfirm">
        确 定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
/**
 * Created by yxk at 2020/6/2
 */
import {
  jxcProductQueryProductSizeAPI,
  jxcProductAddProductSizeAPI
} from '@/api/jxc/product'
import { jxcFieldOnlyAPI, jxcFieldOderNumberOnlyAPI, jxcFieldFindFieldNameAPI } from '@/api/jxc/field'
import JxcTypes from '../../jxcTypes'

export default {
  name: 'AddSize',
  props: {
    value: {
      type: Boolean,
      default: false
    },
    batchId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      loading: false,

      typeObj: JxcTypes.jxc_product,
      data: {},
      autoGeneNumber: false,

      fieldList: [],
      formDataList: [],
      dataList: []
    }
  },
  watch: {
    value: {
      handler() {
        if (this.value) {
          this.getData()
        }
      },
      immediate: true
    }
  },
  created() {
    this.getNumberStatus()
  },
  methods: {
    getNumberStatus() {
      jxcFieldFindFieldNameAPI({
        label: this.typeObj.label,
        fieldName: 'productCode'
      }).then(res => {
        console.log('res: ', res)
        this.autoGeneNumber = res.state == 1
      }).catch(() => {})
    },

    getData() {
      this.loading = true
      jxcProductQueryProductSizeAPI({
        batchId: this.batchId
      }).then(res => {
        this.loading = false
        this.formatData(res.data)
      }).catch(() => {
        this.loading = false
      })
    },

    formatData(data) {
      console.log('res size: ', data)
      this.data = data.jxcProductSpecificationsList[0]

      this.fieldList = data.jxcProductSpecificationsList.map(o => {
        return {
          label: o.specificationsName,
          prop: o.specificationsName,
          data: o
        }
      })
      this.fieldList.push({
        label: '编码',
        prop: 'spDataCode'
      })
      this.dataList = data.jxcProductSpecificationsDataList
    },

    handleAddSize() {
      this.formDataList.push({})
    },
    handleDelete(index) {
      this.formDataList.splice(index, 1)
    },

    handleClose() {
      this.$emit('input', false)
    },

    async handleConfirm() {
      this.loading = true
      const typeArr = this.fieldList.filter(o => o.data).map(o => o.label)
      const arr = []
      for (let i = 0; i < this.formDataList.length; i++) {
        const item = this.formDataList[i]
        let checkFlag = false
        let str = ''
        typeArr.forEach(type => {
          if (item[type]) {
            checkFlag = true
          }
          if (item[type]) {
            str += `${type}:${item[type]};`
          }
        })
        if (!checkFlag) {
          this.$message.error('规格值至少有一个不能为空!')
          return
        }
        arr.push({
          ...item,
          spDataSort: this.dataList.length + i,
          spDataValue: str,
          batchId: this.data.batchId
        })
      }

      const codeList = arr.map(o => o.spDataCode) // 新增的
      const dataCodeList = this.dataList.map(o => o.spDataCode) // 原有的
      const allCodeList = [...codeList, ...dataCodeList] // 全部
      const filterCodeList = allCodeList.filter(o => !!o)
      if (filterCodeList.length !== Array.from(new Set(filterCodeList)).length) {
        this.loading = false
        this.$message.error('产品编号不能重复')
        return
      }
      const promiseArr = []
      let hasEmpty = false
      codeList.forEach(code => {
        const p = {
          fieldName: 'productCode',
          fieldType: 1,
          label: this.typeObj.label,
          value: code
        }
        if (this.batchId) {
          p.batchId = this.batchId
        }
        if (!code && this.autoGeneNumber) {
          hasEmpty = true
        } else {
          promiseArr.push(jxcFieldOnlyAPI(p))
        }
      })
      if (hasEmpty) {
        promiseArr.push(jxcFieldOderNumberOnlyAPI({
          label: this.typeObj.label
        }))
      }
      let error = null
      await Promise.all(promiseArr).then(resArr => {
        const find = resArr.find(o => !o.data)
        if (find) {
          error = true
          return Promise.reject()
        }
      }).catch(() => {
        error = true
      })
      if (error) {
        this.loading = false
        this.$message.error('产品编号不能重复')
        return
      }

      const params = {
        jxcProductSpecificationsDataList: arr,
        batchId: this.batchId
      }
      console.log('save: ', params)

      // this.loading = false
      jxcProductAddProductSizeAPI(params).then(() => {
        this.loading = false
        this.$message.success('添加成功')
        this.$emit('update')
        this.handleClose()
        this.data = {}
        this.fieldList = []
        this.formDataList = []
        this.dataList = []
      }).catch(() => {
        this.loading = false
      })
    }
  }
}
</script>

<style scoped lang="scss">
  /deep/ .el-dialog__body {
    padding: 20px 0;
  }
  .add-size {
    max-height: 50vh;
    padding: 0 20px;
    overflow-x: hidden;
    overflow-y: auto;
    .el-table {
      .el-input {
        margin: 10px 0;
      }
    }
    .add-column {
      border: 1px solid #EBEEF5;
      border-top: 0 none;
      padding: 5px 0 5px 50px;
    }

    .system-table {
      border-bottom: 1px solid #EBEEF5;
      margin-top: 30px;
    }
  }
</style>
